package com.example.tool.util.ems;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * EMS运单轨迹查询工具 (基于Hutool HttpUtil)
 */
public class EMSApiUtil {

    // 接口配置常量
    private static final String API_URL = "https://api.ems.com.cn/amp-prod-api/f/amp/api/open";
    private static final String API_CODE = "040001";
    private static final String SENDER_NO = "1100210532588";
    private static final String AUTH_CODE = "Sj6oIlaYoimJ4HqF";
    private static final String  SECRET_KEY = "U2tUUjdxeXNReHE4dFI3QQ==";
    private static final DateTimeFormatter TIME_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 查询运单轨迹
     * @param waybillNo 运单号 (必填)
     * @param queryReturnTrack 是否查询返单轨迹
     * @return 接口原始响应字符串
     */
    public static JSONObject queryLogistics(String waybillNo, boolean queryReturnTrack) {
        // 1. 参数校验
        if (waybillNo == null || waybillNo.trim().isEmpty()) {
            throw new IllegalArgumentException("运单号不能为空");
        }

        // 2. 构建请求参数
        Map<String, Object> paramMap = queryLogisticsBuildParams(waybillNo, queryReturnTrack);

        // 3. 发送POST请求 (自动处理x-www-form-urlencoded编码)
        return JSONObject.parseObject(HttpUtil.post(API_URL, paramMap));
    }
    /**
     * 查询运单轨迹
     * @param waybillNo 运单号 (必填)
     * @return 接口原始响应字符串
     */
    public static JSONObject queryLogistics(String waybillNo) {
        return queryLogistics(waybillNo, false);
    }
    /**
     * 构建请求参数Map
     */
    private static Map<String, Object> queryLogisticsBuildParams(String waybillNo, boolean queryReturnTrack) {
        Map<String, Object> params = new HashMap<>();

        // 固定参数
        params.put("apiCode", API_CODE);
        params.put("senderNo", SENDER_NO);
        params.put("authorization", AUTH_CODE);
        params.put("timeStamp", LocalDateTime.now().format(TIME_FORMATTER));
        // 动态报文参数
        JSONObject logisticsInterface = new JSONObject ();
        logisticsInterface.put("waybillNo", waybillNo.trim());
        logisticsInterface.put("direction", queryReturnTrack ? "1" : "0");
        String content = logisticsInterface.toString()+SECRET_KEY;
        String encryptStr = CryptoThirdSM4Tools.sm4Encrypt(content, SECRET_KEY);
        params.put("logitcsInterface", encryptStr);
        return params;
    }
    /**
     * 构建请求参数Map
     */
    private static Map<String, Object> trackSubSubscribeBuildParams(String waybillNo, boolean queryReturnTrack) {
        Map<String, Object> params = new HashMap<>();

        // 固定参数
        params.put("apiCode", API_CODE);
        params.put("senderNo", SENDER_NO);
        params.put("logisticsOrderNo", waybillNo);
//        params.put("waybillNo", SENDER_NO);
        params.put("waybillNo", waybillNo);
        params.put("authorization", AUTH_CODE);
        params.put("timeStamp", LocalDateTime.now().format(TIME_FORMATTER));
        // 动态报文参数
        JSONObject logisticsInterface = new JSONObject ();
        logisticsInterface.put("waybillNo", waybillNo.trim());
        logisticsInterface.put("direction", queryReturnTrack ? "1" : "0");
        String content = logisticsInterface.toString()+SECRET_KEY;
        String encryptStr = CryptoThirdSM4Tools.sm4Encrypt(content, SECRET_KEY);
        params.put("logitcsInterface", encryptStr);
        return params;
    }
    /**
     * 订阅物流单号
     * @param waybillNo 物流单号
     */
    public static JSONObject trackSubSubscribe(String waybillNo){
        // 1. 参数校验
        if (waybillNo == null || waybillNo.trim().isEmpty()) {
            throw new IllegalArgumentException("运单号不能为空");
        }

        // 2. 构建请求参数
        Map<String, Object> paramMap = trackSubSubscribeBuildParams(waybillNo,false);

        // 3. 发送POST请求 (自动处理x-www-form-urlencoded编码)
        return JSONObject.parseObject(HttpUtil.post(API_URL, paramMap));
    }

    public static void main(String[] args) {
        System.out.println(trackSubSubscribe("1347825587430"));
    }
    public static String sm4Decrypt(String data){
        return CryptoThirdSM4Tools.sm4Decrypt(data,SECRET_KEY);
    }
//    public static void main(String[] args) {
//        trackSubSubscribe("1347825587430");
//    }
    /**
     * 测试方法
     */
    /*public static void main(String[] args) {
        // 测试用例
        String waybillNo = "1347825587430";
        boolean queryReturn = false;

        try {
            // 调用查询
            JSONObject entries = queryLogistics(waybillNo);

            // 美化输出结果
            System.out.println("=== 请求参数 ===");
            System.out.println("运单号: " + waybillNo);
            System.out.println("查询返单: " + queryReturn);

            System.out.println("\n=== 响应结果 ===");
            System.out.println(JSONUtil.toJsonPrettyStr(entries));

            // 实际使用时可以进一步解析JSON
            JSONObject result = JSONUtil.parseObj(entries);
            System.out.println("\n解析后的code: " + result.getStr("code"));

        } catch (Exception e) {
            System.err.println("查询失败: " + e.getMessage());
            e.printStackTrace();
        }
    }*/
}
